package logic

import (
	"context"
	"smart-health-platforms/config"
	"user_srv/internal/dao"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type ChatTalkLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewChatTalkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChatTalkLogic {
	return &ChatTalkLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ChatTalkLogic) ChatTalk(in *user.ChatTalkRequest) (*user.ChatTalkResponse, error) {
	userID := in.UserId
	sessionDao := dao.NewChatSessionDao(config.DB)
	msgDao := dao.NewChatMessageDao(config.DB, l.svcCtx.Config)

	sessionID := in.SessionId
	if sessionID == 0 { // 新建
		title := in.Content
		if len(title) > 20 { // 标题最多 20 个字符
			title = title[:20]
		}

		id, err := sessionDao.CreateSession(l.ctx, userID, title)
		if err != nil {
			return nil, err
		}
		sessionID = id
	}

	// 对话
	reply, err := msgDao.Talk(l.ctx, sessionID, in.Content)
	if err != nil {
		return nil, err
	}

	if err = msgDao.SavePair(l.ctx, sessionID, in.Content, reply); err != nil {
		return nil, err
	}
	return &user.ChatTalkResponse{SessionId: sessionID, Reply: reply}, nil

}
